#!/usr/bin/env python
#-*- encoding=utf8 -*-
import os, sys, datetime,re
from DBConnection import IQConnection
import settings


def match_ornot(SubStrList,Str):
    flag = True
    for substr in SubStrList:
        if not (substr in Str):
            flag = False
    return flag


class Stockin:
    def __init__(self):
        self.conn = IQConnection(settings.IQ_CONNECT)
        self.columns_tuple = settings.COLUMNS
        self.target_table = settings.TARGET_TABLE_NAME
        self.separator = settings.FIELDS_SEPARATOR
        self.end_symbol = settings.END_SYMBOL

    def get_files(self,FindPath,FlagStr=[]):
        FileList = []
        FileNames = os.listdir(FindPath)
        if (len(FileNames) > 0):
            for fn in FileNames:
                if (len(FlagStr) > 0):
                    if (match_ornot(FlagStr, fn)):
                        fullfilename = os.path.join(FindPath ,fn)
                        FileList.append(fullfilename)
                else:
                    fullfilename = os.path.join(FindPath,fn)
                    FileList.append(fullfilename)
        if(len(FileList) > 0):
            FileList.sort()
        return FileList


    def stockin_exec(self,full_file_name):
        if not self.conn.object_exists(self.target_table):
            self.conn.create_table(self.target_table)
        self.conn.load_table(full_file_name,self.target_table,self.separator,self.end_symbol,self.columns_tuple)
        retlog = full_file_name+' to '+self.target_table+'\n'
        return retlog


